﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CCWin;
using CCWin.SkinControl;
using System.Net;
using System.IO;
using Mes.仓库管理.WareHouse;
using Mes.采购管理;
namespace Mes
{
    public partial class login : CCSkinMain
    {
        public login()
        {
            InitializeComponent();
        }

        // === 配置你的接口信息（按需修改） ===
        private const string ApiBaseUrl = "http://10.223.8.11:8080/"; // Swagger Servers 里的地址，以 / 结尾
        private const string LoginPath = "api/Management/Login"; // 登录接口的相对路径
        private const string UsernameField = "admin";   // 登录请求体里的用户名字段名
        private const string PasswordField = "pwd";   // 登录请求体里的密码字段名

        // 全局 token（登录成功后保存）
        public static string CurrentToken;

        private void skinButton1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtadmin.Text))
            {
                MessageBox.Show("用户名不能为空");
                return;
            }
            //密码不可以为空
            if (string.IsNullOrEmpty(this.txtpwd.Text))
            {
                MessageBox.Show("密码不能为空");
                return;
            }

            try
            {
                string username = this.txtadmin.Text.Trim();
                string password = this.txtpwd.Text;

                Uri baseUri = new Uri(ApiBaseUrl);
                Uri loginUri = new Uri(baseUri, LoginPath);
                string body = "{\"" + UsernameField + "\":\"" + username + "\",\"" + PasswordField + "\":\"" + password + "\"}";

                string resp = HttpPostJson(loginUri.ToString(), body);
                string token = ExtractToken(resp);
                if (string.IsNullOrEmpty(token))
                {
                    MessageBox.Show("账号或密码错误");
                    return;
                }
                CurrentToken = token;
                MessageBox.Show("登录成功");

                var menu = new Menu();
                // 关闭主界面时，退出登录窗体
                menu.FormClosed += (s, args) => this.Close();
                this.Hide();
                menu.Show();
            }
            catch (WebException wex)
            {
                HttpWebResponse resp = wex.Response as HttpWebResponse;
                if (resp != null && (int)resp.StatusCode == 500)
                {
                    MessageBox.Show("账号或密码错误");
                    return;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("登录失败");
            }
        }

        private static string HttpPostJson(string url, string jsonBody)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json";
            req.Accept = "text/plain"; // Swagger 示例要求
            byte[] payload = Encoding.UTF8.GetBytes(jsonBody);
            req.ContentLength = payload.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(payload, 0, payload.Length);
            }
            using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
            using (Stream respStream = resp.GetResponseStream())
            using (StreamReader reader = new StreamReader(respStream, Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        private static string ExtractToken(string json)
        {
            if (string.IsNullOrEmpty(json)) return null;

            int key = json.IndexOf("\"token\"");
            if (key < 0) return null;
            int colon = json.IndexOf(':', key);
            if (colon < 0) return null;
            int firstQuote = json.IndexOf('"', colon);
            if (firstQuote < 0) return null;
            int endQuote = json.IndexOf('"', firstQuote + 1);
            if (endQuote < 0) return null;
            return json.Substring(firstQuote + 1, endQuote - firstQuote - 1);
        }
    }
}
